/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("storagelocationmodel",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Core.Utilities;
using System.Linq;

namespace VOL.demo.Controllers
{
    public partial class storagelocationmodelController
    {
        private readonly IstoragelocationmodelService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public storagelocationmodelController(
            IstoragelocationmodelService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 添加库位
        /// </summary>
        /// <param name="storageLocation">库位信息</param>
        /// <returns>操作结果</returns>
        [HttpPost("Add")]
        public async Task<ActionResult<WebResponseContent>> AddStorageLocation([FromBody] storagelocationmodel storageLocation)
        {
            try
            {
                var result = await _service.AddStorageLocationAsync(storageLocation);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"添加库位失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新库位
        /// </summary>
        /// <param name="storageLocation">库位信息</param>
        /// <returns>操作结果</returns>
        [HttpPost("UpdateStorageLocation")]
        public async Task<ActionResult<WebResponseContent>> UpdateStorageLocation([FromBody] storagelocationmodel storageLocation)
        {
            try
            {
                var result = await _service.UpdateStorageLocationAsync(storageLocation);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"更新库位失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 删除库位
        /// </summary>
        /// <param name="id">库位ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("Delete/{id}")]
        public async Task<ActionResult<WebResponseContent>> DeleteStorageLocation(int id)
        {
            try
            {
                var result = await _service.DeleteStorageLocationAsync(id);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"删除库位失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除库位
        /// </summary>
        /// <param name="ids">库位ID列表</param>
        /// <returns>操作结果</returns>
        [HttpPost("BatchDelete")]
        public async Task<ActionResult<WebResponseContent>> BatchDeleteStorageLocation([FromBody] List<int> ids)
        {
            try
            {
                var result = await _service.BatchDeleteStorageLocationAsync(ids);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"批量删除库位失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据ID获取库位信息
        /// </summary>
        /// <param name="id">库位ID</param>
        /// <returns>库位信息</returns>
        [HttpGet("GetById/{id}")]
        public async Task<ActionResult<storagelocationmodel>> GetStorageLocationById(int id)
        {
            try
            {
                var result = await _service.GetStorageLocationByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { Message = "库位不存在" });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = $"获取库位信息失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 检查库位编号是否存在
        /// </summary>
        /// <param name="locationCode">库位编号</param>
        /// <param name="excludeId">排除的ID（可选）</param>
        /// <returns>是否存在</returns>
        [HttpGet("CheckLocationCode")]
        public async Task<ActionResult<bool>> CheckLocationCodeExists(string locationCode, int? excludeId = null)
        {
            try
            {
                var exists = await _service.IsLocationCodeExistsAsync(locationCode, excludeId);
                return Ok(new { exists = exists, message = exists ? "库位编号已存在" : "库位编号可用" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Message = $"检查库位编号失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取库位分页列表
        /// </summary>
        /// <param name="pageIndex">页码，默认1</param>
        /// <param name="pageSize">每页记录数，默认20</param>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="warehouseId">仓库ID</param>
        /// <param name="locationState">库位状态</param>
        /// <returns>分页结果</returns>
        [HttpGet("GetPagedList")]
        public async Task<ActionResult> GetStorageLocationPagedList(
            int pageIndex = 1,
            int pageSize = 20,
            string keyword = null,
            long? warehouseId = null,
            string locationState = null)
        {
            try
            {
                var result = await _service.GetStorageLocationPagedAsync(pageIndex, pageSize, keyword, warehouseId, locationState);
                
                var response = new
                {
                    success = true,
                    data = result.Data,
                    totalCount = result.TotalCount,
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    totalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize),
                    hasPreviousPage = pageIndex > 1,
                    hasNextPage = pageIndex < Math.Ceiling((double)result.TotalCount / pageSize),
                    message = "获取库位列表成功"
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"获取库位列表失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有可用库位列表（用于下拉选择）
        /// </summary>
        /// <param name="warehouseId">仓库ID（可选）</param>
        /// <returns>库位选项列表</returns>
        [HttpGet("GetOptions")]
        public async Task<ActionResult> GetStorageLocationOptions(long? warehouseId = null)
        {
            try
            {
                var result = await _service.GetStorageLocationPagedAsync(1, 1000, null, warehouseId, "可用");
                
                var response = new
                {
                    success = true,
                    data = result.Data.Select(x => new
                    {
                        id = x.Id,
                        locationCode = x.locationCode,
                        locationName = x.locationName,
                        warehouseId = x.warehouseId,
                        locationState = x.locationState,
                        value = x.Id, // 用于前端select组件的value
                        label = $"{x.locationCode} - {x.locationName}" // 用于前端select组件的label
                    }),
                    message = "获取库位选项成功"
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = $"获取库位选项失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 启用/禁用库位
        /// </summary>
        /// <param name="id">库位ID</param>
        /// <param name="state">库位状态</param>
        /// <returns>操作结果</returns>
        [HttpPost("UpdateState")]
        public async Task<ActionResult<WebResponseContent>> UpdateStorageLocationState(int id, string state)
        {
            try
            {
                var storageLocation = await _service.GetStorageLocationByIdAsync(id);
                if (storageLocation == null)
                {
                    return NotFound(new WebResponseContent { Status = false, Message = "库位不存在" });
                }

                storageLocation.locationState = state;
                var result = await _service.UpdateStorageLocationAsync(storageLocation);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"更新库位状态失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 批量修改库位
        /// </summary>
        /// <param name="dto">批量修改参数</param>
        /// <returns>操作结果</returns>
        [HttpPost("BatchUpdate")]
        [AllowAnonymous]  // 允许匿名访问，不需要JWT验证
        public async Task<ActionResult<WebResponseContent>> BatchUpdateStorageLocation([FromBody] BatchUpdateStorageLocationDto dto)
        {
            try
            {
                var result = await _service.BatchUpdateStorageLocationAsync(dto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"批量修改库位失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 批量修改库位的仓库ID
        /// </summary>
        /// <param name="dto">批量修改仓库参数</param>
        /// <returns>操作结果</returns>
        [HttpPost("BatchUpdateWarehouseId")]
        [AllowAnonymous]  // 允许匿名访问，不需要JWT验证
        public async Task<ActionResult<WebResponseContent>> BatchUpdateWarehouseId([FromBody] BatchUpdateWarehouseDto dto)
        {
            try
            {
                var result = await _service.BatchUpdateWarehouseIdAsync(dto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new WebResponseContent { Status = false, Message = $"批量修改库位仓库ID失败：{ex.Message}" });
            }
        }
    }
}
